package com.syh.niceweibo.data;

import java.util.ArrayList;

import android.database.Cursor;

import com.syh.niceweibo.common.Constants;
import com.syh.niceweibo.common.LogUtils;
import com.syh.niceweibo.common.infos.HotWeiboInfo;
import com.syh.niceweibo.common.infos.UserInfo;
import com.syh.niceweibo.common.infos.WeiboInfo;

/**
 * @author: jinping.lin Revision History: <<Date>> <<Who>> <<What>> 06 11, 2012
 *          jinping.lin initial version
 */
public class HotWeiboDao {

	private static final String TAG = "HotWeiboInfoDao";
	private DBadapter db;

	public HotWeiboDao(DBadapter db) {
		this.db = db;
	}

	public synchronized ArrayList<HotWeiboInfo> queryWeiboList() {
		ArrayList<HotWeiboInfo> result = null;
		Cursor cc = null;
		try {
			result = new ArrayList<HotWeiboInfo>();
			String sql = "select *  from " + Constants.TABLE_HOT_WEIBO
					+ " order by time desc ";
			cc = db.rawQuery(sql.toString(), null);
			if (cc.moveToFirst())
				do {
					result.add(changeCursorToWeibo(cc));
				} while (cc.moveToNext());
		} catch (Exception e) {
			e.printStackTrace();
			if (LogUtils.DEBUG)
				LogUtils.e(TAG, "queryWeiboList e:" + e.toString());
		} finally {
			if (null != cc) {
				try {
					cc.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public static HotWeiboInfo changeCursorToWeibo(Cursor c) {
		HotWeiboInfo result = new HotWeiboInfo();
		UserInfo user = new UserInfo();
		user.uid = c.getLong(c.getColumnIndex("uid"));
		user.screen_name = c.getString(c.getColumnIndex("screen_name"));
		user.profile_image_url = c.getString(c
				.getColumnIndex("profile_image_url"));

		WeiboInfo weibo = new WeiboInfo();
		weibo.weiboId = c.getLong(c.getColumnIndex("weiboId"));
		weibo.content = c.getString(c.getColumnIndex("content"));
		weibo.created_at = c.getLong(c.getColumnIndex("created_at"));
		weibo.original_pic = c.getString(c.getColumnIndex("original_pic"));

		result.userInfo = user;
		result.weiboInfo = weibo;
		return result;
	}

}
